package com.xxxx.comment.controller;


import cn.hutool.core.bean.BeanUtil;
import com.xxxx.comment.entity.User;
import com.xxxx.comment.entity.UserInfo;
import com.xxxx.comment.entity.dto.LoginFormDTO;
import com.xxxx.comment.entity.dto.Result;
import com.xxxx.comment.entity.dto.UserDTO;
import com.xxxx.comment.service.IUserInfoService;
import com.xxxx.comment.service.IUserService;
import com.xxxx.comment.utils.UserHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 前端控制器
 *
 * @author lzf
 * @since 2023/7/9 18:25:09
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        return userService.sendCode(phone, session);
    }

    /**
     * 登录功能
     *
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@Valid @RequestBody LoginFormDTO loginForm, HttpSession session) {
        return userService.login(loginForm, session);
    }

    /**
     * 登出功能
     *
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout() {
        return userService.logout();
    }

    @GetMapping("/me")
    public Result me() {
        // 获取当前登录的用户并返回
        UserDTO user = UserHolder.getUser();
        user.setId(null);

        return Result.ok(user);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") String userId) {
        UserInfo info;
        if ("undefined".equals(userId))
            info = userInfoService.getById(UserHolder.getUser().getId());
        else
            info = userInfoService.getById(userId); // 查询详情
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);

        return Result.ok(info);
    }

    @GetMapping("/{id}")
    public Result queryUserById(@PathVariable("id") Long userId) {
        User user = userService.getById(userId);

        return Result.ok(user != null ? BeanUtil.copyProperties(user, UserDTO.class) : null);
    }

    @PostMapping("/sign")
    public Result sign() {
        return userService.sign();
    }

    @GetMapping("/sign/count")
    public Result signCount() {
        return userService.signCount();
    }

}
